# -*- coding: utf-8 -*-
"""
Created on Thu May  5 19:39:17 2022

@author: Apple
"""

import os
import sys
from PyQt5.QtWidgets import (QAbstractItemView,QMainWindow,QWidget,QTableWidget,QHBoxLayout,QMessageBox,QApplication,QTableWidgetItem,QHeaderView)
from main_window import Ui_MainWindow
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap
import pandas as pd
import numpy as np
import math
import matplotlib.pyplot as plt
import re

class MainWindow(QMainWindow):
    def __init__(self,parent=None):
        super(MainWindow,self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        
        self.ui.actionopenfile.triggered.connect(self.openfile)
        self.ui.actionversion.triggered.connect(self.showversion)
        self.ui.btn11_2.clicked.connect(self.set_var)
        self.ui.btn21.clicked.connect(self.set_func)
        self.ui.btn12_2.clicked.connect(lambda:self.savedata(tw1))
        self.ui.btn22.clicked.connect(lambda:self.savedata(tw2))
        self.ui.btn13_2.clicked.connect(lambda:self.cleartable(1))
        self.ui.btn23.clicked.connect(lambda:self.cleartable(2))
        self.ui.btn32.clicked.connect(self.draw)
        self.ui.btn34.clicked.connect(lambda:self.clearGraph(self.ui.label_pic))
        
        tw1 = self.ui.tableWidget1
        tw1.setRowCount(1)
        tw1.setColumnCount(1)
        tw1.setHorizontalHeaderLabels(['变量'])
        tw1.setEditTriggers(QTableWidget.CurrentChanged)
        newItem = QTableWidgetItem('')
        newItem.setTextAlignment(Qt.AlignCenter)
        tw1.setItem(0,0,newItem)
    
        tw2 = self.ui.tableWidget2
        tw2.setRowCount(1)
        tw2.setColumnCount(3)
        tw2.setHorizontalHeaderLabels(['表达式1','不等式符号','表达式2'])
        tw2.setEditTriggers(QTableWidget.CurrentChanged)
        for i in range(3):
            newItem = QTableWidgetItem('')
            newItem.setTextAlignment(Qt.AlignCenter)
            tw1.setItem(0,i,newItem)
        
    # 打开本地文件
    def openfile(self):
        path = os.getcwd() 
        os.startfile(path)
    
    # 展示当前版本
    def showversion(self):
        QMessageBox.about(self, '关于', '当前版本为 V1.0 ')
        
    # 设置变量数量
    def set_var(self):
        num = self.ui.lineEdit1.text()
        tw = self.ui.tableWidget1
        if num.isdigit() != True :
            print('Please input an *integer*')
            QMessageBox.about(self, '警告', '请输入一个正整数')
            return
        title = []
        for i in range(int(num)):
            title.append('变量%d'%(i+1))
        
        tw.setRowCount(1)
        tw.setColumnCount(int(num))
        tw.setHorizontalHeaderLabels(title)
        tw.setEditTriggers(QTableWidget.CurrentChanged)
        
        for i in range(int(num)):
            newItem = QTableWidgetItem('')
            newItem.setTextAlignment(Qt.AlignCenter)
            tw.setItem(0,i,newItem)
    
    # 设置变量数量
    def set_func(self):
        num = self.ui.lineEdit2.text()
        tw = self.ui.tableWidget2
        if num.isdigit() != True :
            print('Please input an *integer*')
            QMessageBox.about(self, '警告', '请输入一个正整数')
            return
        
        tw.setRowCount(int(num))
        tw.setColumnCount(3)
        tw.setHorizontalHeaderLabels(['表达式1','不等式符号','表达式2'])
        tw.setEditTriggers(QTableWidget.CurrentChanged)
        
        for i in range(int(num)):
            for j in range(3):
                newItem = QTableWidgetItem('')
                newItem.setTextAlignment(Qt.AlignCenter)
                tw.setItem(i,j,newItem)
            
    # 保存当前输入
    def savedata(self,tw):
        tableWidget = tw
        numrow = tableWidget.rowCount()
        numcol = tableWidget.columnCount()
        listall = []
        for i in range(numrow):
            listcol = []
            for j in range(numcol):
                data = tableWidget.item(i,j).text()
                if data =='':
                    QMessageBox.about(self, '警告', '请输入完整数据')
                    return
                else:
                    listcol.append(data)
            listall.append(listcol)
        # print(listall)
        path = os.getcwd() + r'\testdata.csv'
        # print(path)
        test = pd.DataFrame(data = listall)
        test.to_csv(path,index=0)
        QMessageBox.about(self, '完成', '保存成功')   
    
    def cleartable(self,model):
        if model == 1:
            tw1 = self.ui.tableWidget1
            tw1.clear()
            tw1.setRowCount(1)
            tw1.setColumnCount(1)
            tw1.setHorizontalHeaderLabels(['变量'])
            tw1.setEditTriggers(QTableWidget.CurrentChanged)
        
        if model == 2:
            tw2 = self.ui.tableWidget2
            tw2.clear()
            tw2.setRowCount(1)
            tw2.setColumnCount(3)
            tw2.setHorizontalHeaderLabels(['表达式1','不等式符号','表达式2'])
            tw2.setEditTriggers(QTableWidget.CurrentChanged)
            for i in range(3):
                newItem = QTableWidgetItem('')
                newItem.setTextAlignment(Qt.AlignCenter)
                tw1.setItem(0,i,newItem)
                
    def randu(self,x0,a,m,t):
        u_list = []
        for i in range(t+1):
            x = a*x0%m
            u = x/m
            # print(u)
            u_list.append(u)
            x0 = x
        return u_list
        

    def cal_func1(self,x,y):
        value = 4*pow((2*x-1),4)+8*pow((2*y-1),8)
        return value

    def cal_func2(self,x,y):
        value = 1+2*pow((2*y-1),3)*pow((3*x-2),2)
        return value

    def compare_value(self,u_list):
        x = []
        y = []
        for i in range(len(u_list)-1):
            a = u_list[i]
            b = u_list[i+1]
            value1 = self.cal_func1(a,b)
            value2 = self.cal_func2(a,b)
            if value1<value2:
                x.append(a)
                y.append(b)
        return x,y
    
    def draw(self):
        
        plt.rcParams['font.sans-serif']=['SimHei']
        plt.rcParams['axes.unicode_minus']=False

        t = int(self.ui.lineEdit3.text())
        a = pow(7,5)
        m = pow(2,31)-1
        x0 = 1
        u_list = self.randu(x0,a,m,t)
        
        x,y = self.compare_value(u_list)
        s = len(x)/t

        plt.figure(figsize=(8,6),dpi=100)
        plt.scatter(x,y)
        plt.title('采样次数为%d次时近似值为%.4f'%(t,s))

        plt.savefig('test.jpg') # 保存图片
        
        pic = QPixmap('test.jpg')
        self.ui.label_pic.setPixmap(pic)
        self.ui.label_pic.setScaledContents(True)
        
    def clearGraph(self,pic):
        pic.clear()
        

if __name__=="__main__":
    app = QApplication(sys.argv)
    win = MainWindow()
    win.show()
    sys.exit(app.exec_())